package com.atguigu.flink.chapter07;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * TODO 5s内水位连续上涨
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/20 14:06
 */
public class Flink26_State_TimerPractice {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 8888)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {   // 指定如何从数据中提取事件时间
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        return element.getTs() * 1000L; // 转换成 毫秒
                                    }
                                })
                );


        SingleOutputStreamOperator<String> resultDS = sensorDS
                .keyBy(sensor -> sensor.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    ValueState<Long> timerTs;
                    ValueState<Integer> lastVC;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        timerTs = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timerTs", Types.LONG));
                        lastVC = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVC", Types.INT,0));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        if (timerTs.value() == null) {
                            // 第一条进来，注册一个5s后的定时器
                            ctx.timerService().registerEventTimeTimer(ctx.timestamp() + 5000L);
                            timerTs.update(ctx.timestamp() + 5000L);
                        }
                        // 与上一条数据比较水位，判断是上升还是下降
                        if (value.getVc() < lastVC.value()) {
                            // 下降
                            // 1.删除原来的定时器
                            ctx.timerService().deleteEventTimeTimer(timerTs.value());
                            // 2.注册新的定时器
                            ctx.timerService().registerEventTimeTimer(ctx.timestamp() + 5000L);
                            timerTs.update(ctx.timestamp() + 5000L);
                        }
                        // 保存水位值，给下一个数据做判断
                        lastVC.update(value.getVc());
                    }


                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        // 触发后，重置保存的 ts，避免影响后面的检测
                        timerTs.clear();
                        out.collect("传感器=" + ctx.getCurrentKey() + "在ts=" + timestamp + "监测到水位连续5s上升");
                    }
                });


        resultDS.print("result");


        env.execute();
    }

}
/*

 */